import math
import os.path

from flask import Blueprint, jsonify, request, json
from models import *

user_bp = Blueprint('user_bp', __name__)

@user_bp.route('/kind_show')
def kind_show():
    data = KindModel.query.all()
    list = [{
        'id': i.id,
        'name': i.name
    }for i in data]
    return jsonify({
        'code': 200,
        'msg': '获取分类成功',
        'data': list
    })

@user_bp.route('/good_show')
def good_show():
    data = GoodsModel.query.all()
    list = [{
        'id': i.id,
        'name': i.name,
        'num': i.num,
        'price': i.price,
        'img': i.img
    }for i in data]
    return jsonify({
        'code': 200,
        'msg': '获取商品成功',
        'data': list
    })

@user_bp.route('/dt/<int:id>')
def dt(id):
    data = GoodsModel.query.filter_by(id=id)
    list = [{
        'id': i.id,
        'name': i.name,
        'num': i.num,
        'price': i.price,
        'img': i.img
    }for i in data]
    return jsonify({
        'code': 200,
        'msg': '获取单条数据成功',
        'data': list
    })

@user_bp.route('/kind/<int:id>')
def kind(id):
    data = GoodsModel.query.filter(GoodsModel.kind_id == id)
    list = [{
        'id': i.id,
        'name': i.name,
        'num': i.num,
        'price': i.price,
        'img': i.img,
        'kind_id': i.kind_id
    }for i in data]
    return jsonify({
        'code': 200,
        'msg': '获取分类下的信息成功',
        'data': list
    })

@user_bp.route('/add', methods=['POST'])
def add():
    data = request.json
    id = data.get('id')
    name = data.get('name')
    num = data.get('num')
    price = data.get('price')
    img = data.get('img')
    kind_id = data.get('kind_id')
    good = GoodsModel(id=id, name=name, num=num, price=price, img=img, kind_id=kind_id)
    db.session.add(good)
    db.session.commit()
    return jsonify({
        'code': 200,
        'msg': '添加成功'
    })

@user_bp.route('/xiu', methods=['PUT'])
def xiu():
    data = json.loads(request.data)
    GoodsModel.query.filter(GoodsModel.id == data['id']).update({
        'id': data['id'],
        'name': data['name'],
        'price': data['price'],
        'num': data['num'],
        'img': data['img']
    })
    db.session.commit()
    return jsonify({
        'code': 200,
        'msg': '修改成功'
    })

@user_bp.route('/dele/<int:id>', methods=['DELETE'])
def dele(id):
    GoodsModel.query.filter(id=id).delete()
    db.session.commit()
    return jsonify({
        'code': 200,
        'msg': '删除成功'
    })

@user_bp.route('/upload', methods=['POST'])
def upload():
    file = request.files.get('file')
    path = os.path.join('static/' + file.filename)
    file.save(path)
    return jsonify({
        'code': 200,
        'msg': '上传文件成功',
        'url': path
    })